const http = require('http')
const fs = require('fs')
const path = require('path')
const url = require('url');

const server = http.createServer()

server.on('request', (req, res) => {
  if (req.url === '/') {
    fs.readFile(path.join(__dirname, '/pageB.html'), 'utf-8', function (err, data) {
      if (err) {
        throw err;
      }
      res.writeHead(200, 'success 666', { 'Content-Type': 'text/html' })
      res.end(data);
    });
  } else if (req.url === '/data') {  // 首页
    readJSONData('/data.json', function (data) {
      res.statusCode = 200
      res.statusMessage = 'success 666'
      res.setHeader('Content-Type', 'application/json; charset=utf-8');
      res.end(JSON.stringify(data));
    });
  }
})

server.listen('8001', () => {
  console.log('http://localhost:8001 服务器已启动');
})

function readJSONData(p, fn) {
  fs.readFile(path.join(__dirname, p), 'utf8', (err, data) => {
    if (err) {
      return console.log(err);
    }
    data = JSON.parse(data);
    fn && fn(data);
  })
}